<script setup lang='ts'>
// historyShow
import { useGetCascade, useHistorySave, useHistoryhCheckOrder } from '@fl/api/add-elevator-api'
import type { cascadeParam } from '@fl/api/add-elevator-api/model/apply-model'
import type { historyEditParam } from '@fl/api/add-elevator-api/model/history-model'
import { SubmitBtn } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { PlusColumn } from 'plus-pro-components'
import showMap from './map.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { useUserStore } from '@fl/store/modules/user'

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const isReadonly = defineModel<boolean>('isReadonly', { required: true })
const info = defineModel<any>('info', { required: true, default: {} })

const { createConfirmModal } = useMessage()
const formRef = ref() // 加梯信息
const formRef0 = ref() // 位置信息
const title = computed(() => {
    if (id.value) {
        if (isReadonly.value) {
            return '历史加梯数据查看'
        }
        else {
            return '历史加梯数据编辑'
        }
    }
    else {
        return '历史加梯数据录入'
    }
})

const isLoading = ref<boolean>(false)
const active = ref('电梯使用登记')
const options = ['电梯使用登记', '竣工验收登记', '档案归档', '补贴申领', '补贴到账']
const userStore = useUserStore()
const cityName = userStore.getOrgInfo?.areaCode === '429006000000' ? '天门' : '武汉'  // 武汉、天门

const initialState = {
    areaCode: '',
    areaName: '',
    streetCode: '',
    streetName: '',
    communityCode: '',
    communityName: '',
    projectId: '',
    projectName: '',
    buildingId: '',
    building: '',
    unitId: '',
    unit: '',
    num: undefined,
    longitude: undefined,
    latitude: undefined,

    userInfo: { files: [], isOrNot: 1 }, // 电梯使用
    completionInfo: { files: [], isOrNot: 1 }, // 竣工验收
    archiveInfo: { files: [], isOrNot: 1 }, // 档案归档
    subsidyApplicationInfo: { isOrNot: 1 }, // 补贴申领
    subsidyReceivedInfo: { files: [], isOrNot: 1 }, // 补贴到账
}
const state = ref<historyEditParam>(cloneDeep(initialState))

const validStatus1 = computed(() => {
    const info = state.value.userInfo
    if (info.isOrNot === 0 || info.formDate && info.files.length > 0 && info.elevatorCode && info.brand && info.useCompany && info.repairCompany && info.entranceFlag) {
        return true
    }
    else {
        return false
    }
})

const validStatus2 = computed(() => {
    const info = state.value.completionInfo
    if (info.isOrNot === 0 || info.formDate && info.files.length > 0) {
        return true
    }
    else {
        return false
    }
})

const validStatus3 = computed(() => {
    const info = state.value.archiveInfo
    if (info.isOrNot === 0 || info.formDate && info.files.length > 0) {
        return true
    }
    else {
        return false
    }
})

const validStatus4 = computed(() => {
    const info = state.value.subsidyApplicationInfo
    if (info.isOrNot === 0 || info.formDate) {
        return true
    }
    else {
        return false
    }
})

const validStatus5 = computed(() => {
    const info = state.value.subsidyReceivedInfo
    if (info.isOrNot === 0 || info.formDate) {
        return true
    }
    else {
        return false
    }
})

// 级联选择
const initialParams = {
    targetLabel: '',
    areaCode: '',
    streetCode: '',
    communityCode: '',
    projectId: '',
    building: '',
    unit: '',
    time: undefined, // 刷新用，每次选择后都调用接口
}
const areaParams = ref<cascadeParam>(cloneDeep(initialParams))
const streetParams = ref<cascadeParam>(cloneDeep(initialParams))
const communityParams = ref<cascadeParam>(cloneDeep(initialParams))
const projectParams = ref<cascadeParam>(cloneDeep(initialParams))
const buildingParams = ref<cascadeParam>(cloneDeep(initialParams))
const unitParams = ref<cascadeParam>(cloneDeep(initialParams))

areaParams.value.targetLabel = 'area'

// 详情
function getApplyShow() {
    state.value = cloneDeep(info.value)
    state.value.buildingId = state.value.building // 第3.4级没返id
    state.value.unitId = state.value.unit
    // 查街道
    streetParams.value.targetLabel = 'street'
    streetParams.value.areaCode = state.value.areaCode
    // 查社区
    communityParams.value.targetLabel = 'community'
    communityParams.value.streetCode = state.value.streetCode
    // 查小区
    projectParams.value.targetLabel = 'project'
    projectParams.value.communityCode = state.value.communityCode
    // 查栋
    buildingParams.value.targetLabel = 'building'
    buildingParams.value.projectId = state.value.projectId
    // 查单元
    unitParams.value.targetLabel = 'unit'
    unitParams.value.building = state.value.building

    console.log('详情', info.value)

    // 加梯信息
    state.value.userInfo = JSON.parse(info.value.userInfo)
    state.value.completionInfo = JSON.parse(info.value.completionInfo)
    state.value.archiveInfo = JSON.parse(info.value.archiveInfo)
    state.value.subsidyApplicationInfo = JSON.parse(info.value.subsidyApplicationInfo)
    state.value.subsidyReceivedInfo = JSON.parse(info.value.subsidyReceivedInfo)

    state.value.latitude = Number(info.value.latitude)
    state.value.longitude = Number(info.value.longitude)
}

watch(() => visible.value, () => {
    if (!visible.value) {
        reset()
    }
    else {
        if (id.value) {
            getApplyShow()
        }
    }
})

watch(() => state.value.unit, (val) => {
    const unit = String(val)
    // 允许输入“无”和英文、数字
    const regex = /^[a-z0-9]+$/i
    if (!regex.test(unit)) {
        state.value.unit = unit.replace(/[^a-z0-9无]/gi, '')
    }
    // 输入纯数字是时，限制200
    const regexNum = /^\d+$/
    if (regexNum.test(unit) && Number(unit) >= 200 && cityName === '武汉') {
        state.value.unit = '200'
    }
})

// 非武汉，楼栋仅允许数字。字母
function handleBuildingInput() {
    state.value.building = state.value.building.replace(/[^a-zA-Z0-9]/g, '');
}

// 下拉框：过滤数据
const areaOptions = ref<any>([])
const streetOptions = ref<any>([])
const communityOptions = ref<any>([])
const projectOptions = ref<any>([])
const buildingOptions = ref<any>([])
const unitOptions = ref<any>([])
const finalUnitOptions = computed(() => {
    const originArr: any = [{ label: '无', value: '无' }]
    for (let i = 1; i <= 200; i++) {
        originArr.push({ label: String(i), value: String(i) })
    }
    // 后端返的列表数据，替换value
    const tempArr = toRaw(unitOptions.value)
    const finalArr = originArr.reduce((pre, cur) => {
        for (let i = 0; i < tempArr.length; i++) {
            if (cur.label === tempArr[i].label) {
                cur.value = tempArr[i].value
            }
        }
        pre.push(cur)
        return pre
    }, [])
    return finalArr
})

// 下拉框：原数据
const buildingOriginOptions = ref<any>([])

const { data: areaList } = useGetCascade(areaParams)
const { data: streetList } = useGetCascade(streetParams)
const { data: communityList } = useGetCascade(communityParams)
const { data: projectList } = useGetCascade(projectParams)
const { data: buildingList } = useGetCascade(buildingParams)
const { data: unitList } = useGetCascade(unitParams)

watchEffect(() => {
    if (areaList.value) {
        areaOptions.value = cloneDeep(areaList.value)
    }
    if (streetList.value) {
        streetOptions.value = cloneDeep(streetList.value)
    }
    if (communityList.value) {
        communityOptions.value = cloneDeep(communityList.value)
    }
    if (projectList.value) {
        projectOptions.value = cloneDeep(projectList.value)
    }
    if (buildingList.value) {
        buildingOptions.value = cloneDeep(buildingList.value)
    }
    if (unitList.value) {
        unitOptions.value = cloneDeep(unitList.value)
    }
})
const isAreaDisabeld = computed(() => {
    return isReadonly.value
})

const isStreetDisabeld = computed(() => {
    return !state.value.areaCode || isReadonly.value
})

const isCommunityDisabeld = computed(() => {
    return isStreetDisabeld.value || !state.value.streetCode || isReadonly.value
})

const isProjectDisabeld = computed(() => {
    return isCommunityDisabeld.value || !state.value.communityCode || isReadonly.value
})
const isBuildingDisabeld = computed(() => {
    return isProjectDisabeld.value || !state.value.projectId || isReadonly.value
})
const isUnitDisabeld = computed(() => {
    return isBuildingDisabeld.value || !state.value.building || isReadonly.value
})

// 清空街道
function clearStreet() {
    state.value.streetCode = ''
    state.value.streetName = ''
    clearCommunity()
}

// 清空社区
function clearCommunity() {
    state.value.communityCode = ''
    state.value.communityName = ''
    clearProject()
}

// 清空小区
function clearProject() {
    state.value.projectId = ''
    state.value.projectName = ''
    clearBuilding()
}

// 清空栋
function clearBuilding() {
    state.value.buildingId = ''
    state.value.building = ''
    clearUnit()
}

// 清空单元
function clearUnit() {
    state.value.unitId = ''
    state.value.unit = ''
    unitOptions.value = []
}

// 1.选择区
function areaChange() {
    // 清空
    state.value.streetCode = ''
    state.value.communityCode = ''
    clearStreet()

    const target = areaOptions.value.find((v: any) => v.value === state.value.areaCode)
    state.value.areaName = target.label
    streetParams.value.targetLabel = 'street'
    streetParams.value.areaCode = state.value.areaCode
    streetParams.value.time = new Date().getTime()
}

// 2.街道选择
function streetChange() {
    // 清空
    state.value.communityCode = ''
    clearCommunity()

    const target = streetOptions.value.find((v: any) => v.value === state.value.streetCode)
    state.value.streetName = target.label
    communityParams.value.targetLabel = 'community'
    communityParams.value.streetCode = state.value.streetCode
    communityParams.value.time = new Date().getTime()
}

// 3.社区选择
function communityChange() {
    // 清空
    state.value.projectId = ''
    clearProject()

    const target = communityOptions.value.find((v: any) => v.value === state.value.communityCode)
    state.value.communityName = target.label
    projectParams.value.targetLabel = 'project'
    projectParams.value.communityCode = state.value.communityCode
    projectParams.value.time = new Date().getTime()
}

// 4.小区选择
function projectChange() {
    // 清空
    state.value.building = ''
    clearBuilding()

    const target = projectOptions.value.find((v: any) => v.value === state.value.projectId)
    state.value.projectName = target.label
    buildingParams.value.targetLabel = 'building'
    buildingParams.value.projectId = state.value.projectId
    buildingParams.value.time = new Date().getTime()
}

// 5.栋选择
function buildingChange() {
    const target = buildingOptions.value.find((v: any) => v.label === state.value.building)
    state.value.buildingId = target?.value || ''
    unitParams.value.targetLabel = 'unit'
    unitParams.value.building = state.value.building
    unitParams.value.time = new Date().getTime()
    // 清空
    clearUnit()
}

// 6.单元选择

// 提交表单
const { isPending, mutate } = useHistorySave()
// 检查在申请单
const { mutate: checkMutate } = useHistoryhCheckOrder()

// 下一步
async function next() {
    await formRef0.value.formInstance.validate()
    if (active.value === '电梯使用登记') {
        await formRef.value.formInstance.validate()
        active.value = '竣工验收登记'
    }
    else if (active.value === '竣工验收登记') {
        await formRef.value.formInstance.validate()
        active.value = '档案归档'
    }
    else if (active.value === '档案归档') {
        await formRef.value.formInstance.validate()
        active.value = '补贴申领'
    }
    else if (active.value === '补贴申领') {
        await formRef.value.formInstance.validate()
        active.value = '补贴到账'
    }
}

// 提交
async function submit() {
    const valid0 = await formRef0.value.formInstance.validate()
    const tempInfo = { files: [], isOrNot: 0 } // 填否时专门转一下
    if (!(valid0 && validStatus1.value && validStatus2.value && validStatus3.value && validStatus4.value && validStatus5.value)) {
        ElMessage.warning('请填写完整表单')
        return
    }
    // 检查在申请单
    const checkParams = {
        projectId: state.value.projectId || null,
        building: state.value.building,
        unit: state.value.unit || state.value.unitId,
    }
    const params = {
        id: id.value ?? '',
        ...unref(state),
        userInfo: state.value.userInfo?.isOrNot ? JSON.stringify(state.value.userInfo) : JSON.stringify(tempInfo),
        completionInfo: state.value.completionInfo?.isOrNot ? JSON.stringify(state.value.completionInfo) : JSON.stringify(tempInfo),
        archiveInfo: state.value.archiveInfo?.isOrNot ? JSON.stringify(state.value.archiveInfo) : JSON.stringify(tempInfo),
        subsidyApplicationInfo: state.value.subsidyApplicationInfo?.isOrNot ? JSON.stringify(state.value.subsidyApplicationInfo) : JSON.stringify(tempInfo),
        subsidyReceivedInfo: state.value.subsidyReceivedInfo?.isOrNot ? JSON.stringify(state.value.subsidyReceivedInfo) : JSON.stringify(tempInfo),

        areaCode: state.value.areaCode || null, // 后端要求传null
        streetCode: state.value.streetCode || null,
        communityCode: state.value.communityCode || null,
        projectId: state.value.projectId || null,
        // unitId: (!state.value.unitId || state.value.unitId === '无') ? null : state.value.unitId,
        unitId: cityName === '武汉' ? state.value.unit || state.value.unitId : '',
        buildingId: cityName === '武汉' ? state.value.buildingId : ''
    }
    checkMutate(checkParams, {
        onSuccess: (res) => {
            if (res.code === 200) {
                // 提交
                mutate(params, {
                    onSuccess: () => {
                        ElMessage.success('操作成功')
                        cancel()
                    },
                })
            }
            else {
                createConfirmModal({
                    content: '该楼栋单元存在有效加梯申请，请确认后补录。',
                    onError: () => {
                        console.log('操作取消！')
                    },
                    onSuccess: () => {
                        // 提交
                        mutate(params, {
                            onSuccess: () => {
                                ElMessage.success('操作成功')
                                cancel()
                            },
                        })
                    },
                })
            }
        },
    })
}

function cancel() {
    visible.value = false
    reset()
}

function reset() {
    id.value = ''
    isReadonly.value = false
    active.value = '电梯使用登记'
    state.value = cloneDeep(initialState)
    formRef0.value?.formInstance.resetFields()
    formRef.value?.formInstance.resetFields()
}

const columns: PlusColumn[] = [
    {
        label: '所在区',
        prop: 'areaCode',
    },
    {
        label: '街道',
        prop: 'streetCode',
    },
    {
        label: '社区',
        prop: 'communityCode',
    },
    {
        label: '小区',
        prop: 'projectId',
    },
    {
        label: '栋',
        prop: 'building',
    },
    {
        label: '单元楼',
        prop: 'unit',
    },
    {
        label: '小区总单元数',
        prop: 'num',
        tooltip: '即小区总楼栋单元数，楼栋数量*各楼栋单元数',
    },
    {
        label: '详细地址',
        prop: 'houseAddr',
    },
]

const rules = computed(() => ({
    areaCode: [
        {
            message: '所在区',
            required: true,
        },
    ],
    streetCode: [
        {
            message: '街道',
            required: true,

        },
    ],
    communityCode: [
        {
            message: '社区',
            required: true,

        },
    ],
    projectId: [
        {
            message: '小区',
            required: true,

        },
    ],
    building: [
        {
            message: '栋',
            required: true,
        },
    ],
    unit: [
        {
            message: '单元楼',
            required: true,
        },
    ],
    num: [
        {
            message: '小区总单元数',
            required: false,

        },
    ],
}))

// 1.电梯使用
const columns1: any = computed(() => {
    return [
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            label: '是否取得电梯使用登记',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            prop: 'isOrNot',
            valueType: 'radio',
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),

            label: '是否平层入户',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 2,
                },
            ],
            prop: 'entranceFlag',
            valueType: 'radio',
        },
        {
            fieldProps: {
                'disabled': computed(() => !!isReadonly.value),
                'placeholder': '请选择时间',
                'format': 'YYYY-MM-DD',
                'type': 'date',
                'valueFormat': 'YYYY-MM-DD',
                'disabled-date': (time: Date) => {
                    return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                },
            },
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '取得电梯使用登记时间',
            prop: 'formDate',
            valueType: 'date-picker',

        },
        {
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '电梯使用登记证',
            prop: 'files',
        },
        {
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '电梯设备代码',
            prop: 'elevatorCode',
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
                maxlength: 30,
                showWordLimit: true,
            },
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '电梯品牌',
            prop: 'brand',
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
                maxlength: 30,
                showWordLimit: true,
            },
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '电梯使用单位',
            prop: 'useCompany',
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
                maxlength: 30,
                showWordLimit: true,
            },
            hideInForm: computed(() => state.value.userInfo.isOrNot === 0),
            label: '电梯维保单位',
            prop: 'repairCompany',
        },
    ]
})

const reg = /^[a-z0-9]+$/i
function validatorpassword(rule, value, callback) {
    // 编辑忽略密码校验
    if (!!value && reg.test(value)) {
        callback()
    }
    else {
        callback(new Error('请输入数字和英文'))
    }
}
const rules1 = computed(() => ({
    isOrNot: [
        { required: true },
    ],
    entranceFlag: [
        {
            required: true,
            trigger: 'change',
            message: '请选择是否平层入户',
        },
    ],
    formDate: [
        {
            required: true,
            trigger: 'change',
            message: '请选择时间',
        },
    ],
    files: [
        {
            required: true,
            trigger: 'change',
            message: '请上传文件',
        },
    ],
    elevatorCode: [
        {
            message: '请输入数字和英文',
            required: true,
            trigger: 'blur',
            validator: validatorpassword,
        },
    ],
    brand: [
        {
            required: true,
            message: '请输入',
        },
    ],
    useCompany: [
        {
            required: true,
            message: '请输入',
        },
    ],
    repairCompany: [
        {
            required: true,
            message: '请输入',
        },
    ],
}))

// 2.竣工验收
const columns2: any = computed(() => {
    return [
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            label: '是否电梯竣工验收登记',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            prop: 'isOrNot',
            valueType: 'radio',
        },
        {
            fieldProps: {
                'disabled': computed(() => !!isReadonly.value),
                'placeholder': '请选择时间',
                'format': 'YYYY-MM-DD',
                'type': 'date',
                'valueFormat': 'YYYY-MM-DD',
                'disabled-date': (time: Date) => {
                    return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                },
            },
            hideInForm: computed(() => state.value.completionInfo.isOrNot === 0),
            label: '取得电梯竣工意见验收表时间',
            prop: 'formDate',
            valueType: 'date-picker',

        },
        {
            hideInForm: computed(() => state.value.completionInfo.isOrNot === 0),
            label: '既有住宅加装电梯竣工意见验收表',
            prop: 'files',
        },
    ]
})

const rules2 = computed(() => ({
    isOrNot: [
        { required: true },
    ],
    formDate: [
        {
            required: true,
            trigger: 'change',
            message: '请选择时间',
        },
    ],
    files: [
        {
            required: true,
            trigger: 'change',
            message: '请上传文件',
        },
    ],
}))

// 3.档案归档
const columns3: any = computed(() => {
    return [
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            label: '是否档案归档',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            prop: 'isOrNot',
            valueType: 'radio',
        },
        {
            fieldProps: {
                'disabled': computed(() => !!isReadonly.value),
                'placeholder': '请选择时间',
                'format': 'YYYY-MM-DD',
                'type': 'date',
                'valueFormat': 'YYYY-MM-DD',
                'disabled-date': (time: Date) => {
                    return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                },
            },
            hideInForm: computed(() => state.value.archiveInfo.isOrNot === 0),
            label: '取得档案归档证明资料时间',
            prop: 'formDate',
            valueType: 'date-picker',

        },
        {
            hideInForm: computed(() => state.value.archiveInfo.isOrNot === 0),
            label: '档案归档证明资料',
            prop: 'files',
        },
    ]
})
const rules3 = computed(() => ({
    isOrNot: [
        { required: true },
    ],
    formDate: [
        {
            required: true,
            trigger: 'change',
            message: '请选择时间',
        },
    ],
    files: [
        {
            required: true,
            trigger: 'change',
            message: '请上传文件',
        },
    ],
}))

// 4.补贴申领
const columns4: any = computed(() => {
    return [
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            label: '是否补贴申领',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            prop: 'isOrNot',
            valueType: 'radio',
        },
        {
            fieldProps: {
                'disabled': computed(() => !!isReadonly.value),
                'placeholder': '请选择时间',
                'format': 'YYYY-MM-DD',
                'type': 'date',
                'valueFormat': 'YYYY-MM-DD',
                'disabled-date': (time: Date) => {
                    return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                },
            },
            hideInForm: computed(() => state.value.subsidyApplicationInfo.isOrNot === 0),
            label: '申领补贴时间',
            prop: 'formDate',
            valueType: 'date-picker',

        },
    ]
})
const rules4 = computed(() => ({
    isOrNot: [
        { required: true },
    ],
    formDate: [
        {
            required: true,
            trigger: 'change',
            message: '请选择时间',
        },
    ],
}))

// 5.补贴到账
const columns5: any = computed(() => {
    return [
        {
            fieldProps: {
                disabled: computed(() => !!isReadonly.value),
            },
            label: '是否补贴到账',
            options: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            prop: 'isOrNot',
            valueType: 'radio',
        },
        {
            fieldProps: {
                'disabled': computed(() => !!isReadonly.value),
                'placeholder': '请选择时间',
                'format': 'YYYY-MM-DD',
                'type': 'date',
                'valueFormat': 'YYYY-MM-DD',
                'disabled-date': (time: Date) => {
                    return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                },
            },
            hideInForm: computed(() => state.value.subsidyReceivedInfo.isOrNot === 0),
            label: '补贴到账时间',
            prop: 'formDate',
            valueType: 'date-picker',

        },
        {
            hideInForm: computed(() => state.value.subsidyReceivedInfo.isOrNot === 0),
            label: '补贴凭证',
            prop: 'files',
        },
    ]
})
const rules5 = computed(() => ({
    isOrNot: [
        { required: true },
    ],
    formDate: [
        {
            required: true,
            trigger: 'change',
            message: '请选择时间',
        },
    ],
}))
</script>

<template>
    <el-drawer v-model="visible"
               :size="600"
    >
        <template #header>
            <div class="text-24 text-black font-600">
                {{ title }}
            </div>
        </template>

        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="plusform mt-20">
                <PlusForm ref="formRef0"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                >
                    <template #plus-field-areaCode>
                        <el-select v-model="state.areaCode"
                                   placeholder="请选择"
                                   filterable
                                   :disabled="isAreaDisabeld"
                                   @change="areaChange"
                        >
                            <el-option v-for="item in areaOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-streetCode>
                        <el-select v-model="state.streetCode"
                                   placeholder="请选择"
                                   filterable
                                   :disabled="isStreetDisabeld"
                                   @change="streetChange"
                        >
                            <el-option v-for="item in streetOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-communityCode>
                        <el-select v-model="state.communityCode"
                                   placeholder="请选择"
                                   filterable
                                   :disabled="isCommunityDisabeld"
                                   @change="communityChange"
                        >
                            <el-option v-for="item in communityOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-projectId>
                        <el-select v-model="state.projectId"
                                   placeholder="请选择"
                                   filterable
                                   :disabled="isProjectDisabeld"
                                   @change="projectChange"
                        >
                            <el-option v-for="item in projectOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-building>

                        <!-- allow-create -->
                        <el-select v-model="state.building"
                                   filterable
                                   clearable
                                   default-first-option
                                   :reserve-keyword="false"
                                   placeholder="请选择/输入"
                                   :disabled="isBuildingDisabeld"
                                   @change="buildingChange"
                                   v-if="cityName==='武汉'"
                        >
                            <el-option v-for="item in buildingOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>

                        <el-input v-else  v-model="state.building" :disabled="isBuildingDisabeld" @input="handleBuildingInput" placeholder="请输入数字或字母" />
                        
                    </template>

                    <template #plus-field-unit>
                        <el-select v-model="state.unit"
                                   filterable
                                   clearable
                                   allow-create
                                   default-first-option
                                   :reserve-keyword="false"
                                   placeholder="请选择/输入"
                                   :disabled="isUnitDisabeld"
                                   v-if="cityName==='武汉'"
                        >
                            <el-option v-for="item in finalUnitOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>

                        <el-input v-else  v-model="state.unit" :disabled="isUnitDisabeld" placeholder="请输入数字或字母或无" />
                    </template>

                    <template #plus-field-num>
                        <el-input v-model="state.num"
                                  oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=''} if(value>99999){value=99999}"
                                  :disabled="isReadonly"
                        />
                    </template>
                </plusform>
            </div>

            <div class="title">
                加梯信息
            </div>

            <div class="flex flex-col gap-4 items-start">
                <el-segmented v-model="active"
                              :options="options"
                />
            </div>

            <div class="mt-20">
                <div v-if="active === '电梯使用登记'">
                    <PlusForm ref="formRef"
                              v-model="state.userInfo"
                              :columns="columns1"
                              :label-width="220"
                              :rules="rules1"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    >
                        <template #plus-field-files>
                            <FlUpload :key="String(active + visible)"
                                      v-model="state.userInfo.files"
                                      :limit="10"
                                      accept="*"
                                      list-type="text"
                                      :tips="false"
                                      :disabled="isReadonly"
                            />
                        </template>
                    </PlusForm>
                </div>

                <div v-else-if="active === '竣工验收登记'">
                    <PlusForm ref="formRef"
                              v-model="state.completionInfo"
                              :columns="columns2"
                              :label-width="240"
                              :rules="rules2"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    >
                        <template #plus-field-files>
                            <FlUpload :key="String(active + visible)"
                                      v-model="state.completionInfo.files"
                                      :limit="10"
                                      accept="*"
                                      list-type="text"
                                      :tips="false"
                                      :disabled="isReadonly"
                            />
                        </template>
                    </PlusForm>
                </div>

                <div v-else-if="active === '档案归档'">
                    <PlusForm ref="formRef"
                              v-model="state.archiveInfo"
                              :columns="columns3"
                              :label-width="220"
                              :rules="rules3"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    >
                        <template #plus-field-files>
                            <FlUpload :key="String(active + visible)"
                                      v-model="state.archiveInfo.files"
                                      :limit="10"
                                      accept="*"
                                      list-type="text"
                                      :tips="false"
                                      :disabled="isReadonly"
                            />
                        </template>
                    </PlusForm>
                </div>

                <div v-else-if="active === '补贴申领'">
                    <PlusForm ref="formRef"
                              v-model="state.subsidyApplicationInfo"
                              :columns="columns4"
                              :label-width="220"
                              :rules="rules4"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    />
                </div>

                <div v-else-if="active === '补贴到账'">
                    <PlusForm ref="formRef"
                              v-model="state.subsidyReceivedInfo"
                              :columns="columns5"
                              :label-width="220"
                              :rules="rules5"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    >
                        <template #plus-field-files>
                            <FlUpload :key="String(active + visible)"
                                      v-model="state.subsidyReceivedInfo.files"
                                      :limit="10"
                                      accept="*"
                                      list-type="text"
                                      :tips="false"
                                      :disabled="isReadonly"
                            />
                        </template>
                    </PlusForm>
                </div>
            </div>

            <div v-if="!isReadonly"
                 class="mx-auto mt20 flex justify-right"
            >
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn v-if="active !== '补贴到账'"
                           type="primary"
                           @click="next"
                >
                    下一步
                </SubmitBtn>

                <SubmitBtn v-if="active === '补贴到账'"
                           type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    提交
                </SubmitBtn>
            </div>

            <!-- 地图 -->
            <div v-if="state?.longitude > 0"
                 class="abs"
            >
                <showMap v-model:longitude="state.longitude"
                         v-model:latitude="state.latitude"
                />
            </div>
        </template>
    </el-drawer>
</template>

<style lang="scss" scoped>
.plusform {
    // height: 640px;
    overflow-y: auto;
    overflow-x: hidden;
}

.positive {
    position: absolute;
    width: 100%;
    max-height: 110px;
    background: #fff;
    z-index: 10;
    top: 34px;
    left: 0;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 4px;

    .item {
        padding-left: 10px;
        cursor: pointer;
    }

    .item:hover {
        background: #eee;
    }
}

.title {
    font-size: 16px;
    font-weight: 600;
    height: 60px;
    line-height: 60px;
}
.abs {
    position: fixed;
    top: 30px;
    right: 624px;
    background: #fff;
    width: calc(96vw - 800px);
    height: 92vh;
}
</style>
